package com;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Image extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public Image() {
		super();
	}

	public static final int NUM = 4;
	public static final String STR = "qwertyuipasdfghjkzxcvbnm123456789һ";
	public static String code = null;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		BufferedImage bufferedImage = new BufferedImage(100, 20, BufferedImage.TYPE_INT_RGB);
		Graphics graphics = bufferedImage.getGraphics();
		graphics.setColor(new Color(43, 37, 85, 225));
		graphics.fillRect(0, 0, 100, 40);
		int length = STR.length();
		Random random = new Random();
		for (int i = 1; i < NUM + 1; i++) {
			int index = random.nextInt(length);
			Character c = STR.charAt(index);
			code += c;
			graphics.setColor(Color.blue);
			graphics.drawString(c.toString(), i * 20, 15);
		}
		request.getSession().setAttribute("code", code);
		graphics.dispose();
		ImageIO.write(bufferedImage, "png", response.getOutputStream());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
